﻿using System.Configuration;
using System.Net.Mail;
using System.Text;

namespace Altairis.MailToolkit.Configuration {

    public class EmailAddressElement : ConfigurationElement {

        /// <summary>
        /// Gets or sets the e-mail address.
        /// </summary>
        /// <value>The e-mail address.</value>
        [ConfigurationProperty("address", IsRequired = true, DefaultValue = "null")]
        [RegexStringValidator(@"^(\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)|(null)$")]
        public string Address {
            get { return (string)this["address"]; }
            set { this["address"] = value; }
        }

        /// <summary>
        /// Gets or sets the display name.
        /// </summary>
        /// <value>The display name.</value>
        [ConfigurationProperty("displayName", IsRequired = false, DefaultValue = "")]
        public string DisplayName {
            get { return (string)this["displayName"]; }
            set { this["displayName"] = value; }
        }

        /// <summary>
        /// Gets or sets the display name encoding.
        /// </summary>
        /// <value>The display name encoding.</value>
        [ConfigurationProperty("displayNameEncoding", IsRequired = false, DefaultValue = "UTF-8")]
        public string DisplayNameEncoding {
            get { return (string)this["displayNameEncoding"]; }
            set { this["displayNameEncoding"] = value; }
        }

        /// <summary>
        /// Gets the e-mail address as instance <see cref="System.Net.Mail.MailAddress"/> class.
        /// </summary>
        /// <value>The e-mail address as instance <see cref="System.Net.Mail.MailAddress"/> class.</value>
        public MailAddress MailAddress {
            get {
                if (string.IsNullOrEmpty(this.Address) || this.Address.Equals("null")) return null;
                return new MailAddress(this.Address, this.DisplayName, Encoding.GetEncoding(this.DisplayNameEncoding));
            }
        }
    }
}